package com.sskj.motherboard.handler.strategy;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sskj.common.constant.RabbitMQConstant;
import com.sskj.common.dto.DeviceQueueMessage;
import com.sskj.common.dto.motherboard.HeartbeatMessage;
import com.sskj.common.enums.DeviceMessageTypeEnum;
import com.sskj.motherboard.constant.ChannelAttributesConstant;
import com.sskj.motherboard.vo.FrameMessage;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Slf4j
@Component
public class HeartbeatHandler implements IFrameMessageHandlerStrategy{

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, FrameMessage frameMessage) {
        String deviceId = channelHandlerContext.channel().attr(ChannelAttributesConstant.DEVICE_ID).get();
        if (deviceId != null && !deviceId.trim().isEmpty()) {
            // 异步消息投递
            HeartbeatMessage heartbeatMessage = new HeartbeatMessage();
            heartbeatMessage.setDeviceId(deviceId);
            heartbeatMessage.setTime(LocalDateTime.now());

            try {
                String payload = objectMapper.writeValueAsString(heartbeatMessage);
                DeviceQueueMessage deviceQueueMessage = new DeviceQueueMessage();
                deviceQueueMessage.setType(DeviceMessageTypeEnum.HEARTBEAT_CHECK.getType());
                deviceQueueMessage.setPayload(payload);

                amqpTemplate.convertAndSend(RabbitMQConstant.IOT_EXCHANGE, RabbitMQConstant.IOT_ROUTEING_KEY, objectMapper.writeValueAsString(deviceQueueMessage));
            } catch (JsonProcessingException e) {
                log.error("序列化异常。异常信息: {}", e.getMessage());
            }
        }

        // 回复注册响应
        FrameMessage replyFrameMessage = new FrameMessage();
        replyFrameMessage.setCommandCode((byte) 0x01);
        replyFrameMessage.setCommandType((byte) 0x81);
        replyFrameMessage.setData(new byte[0]);
        channelHandlerContext.channel().writeAndFlush(replyFrameMessage);
    }
}
